package com.taotie.task;

import com.taotie.constant.MessageConstant;
import com.taotie.constant.OrdersConstant;
import com.taotie.entity.Orders;
import com.taotie.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 支付订单超时处理
     * 下单超过15分钟未支付默认取消
     * 每分钟执行一次定时器
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOutOrder() {
        log.info("支付超时订单处理:{}", LocalDateTime.now());
        //获取超时15分钟的订单
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-15);
        Integer status = OrdersConstant.DUE;
        List<Orders> timeOutOrders = orderMapper.getByStatusAndOrderTime(status, orderTime);
        if (timeOutOrders != null && !timeOutOrders.isEmpty()) {
            //将超时订单取消
            for (Orders order : timeOutOrders) {
                //将订单状态设置为取消
                order.setStatus(OrdersConstant.CANCELLED);
                //设置订单取消时间和原因等
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason(MessageConstant.ORDER_TIME_OUT);
                orderMapper.update(order);
            }
        }


    }

    /**
     * 定时处理深夜订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder() {
        log.info("未完成订单处理:{}", LocalDateTime.now());
        //获取凌晨订单,订单状态为“派送中”
        LocalDateTime nightTime = LocalDateTime.now().plusMinutes(-60);
        Integer status = OrdersConstant.OUT_OF_DELIVERY;
        List<Orders> nightOrders = orderMapper.getByStatusAndOrderTime(status, nightTime);
        if (nightOrders != null && !nightOrders.isEmpty()) {
            for (Orders order : nightOrders) {
                //将订单状态设置为取消
                order.setStatus(OrdersConstant.CANCELLED);
                //设置订单取消时间和原因等
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason(MessageConstant.LATE_NIGHT_ORDER);
                orderMapper.update(order);
            }

        }
    }
}
